<template>
	<view>
		<!-- grace filter start -->
		<view class="grace-filter" id="grace-filter-header">
			<view class="items" @tap='showOptions1'><block v-if="facetDatabase.length>0">{{facetDatabase[dbIndex].name}}</block><text class="grace-iconfont icon-arrow-down"></text></view>
			<view class="items" @tap='showOptions2'><block v-if="cateList.length>0">{{cateList[cateIndex].name}}</block><text class="grace-iconfont icon-arrow-down"></text></view>
			<view class="items" @tap='showOptions3'>{{thList[thIndex]}}<text class="grace-iconfont icon-arrow-down"></text></view>
			 
			<view class="items" @tap='showOptions99'>筛选<text class="grace-iconfont icon-shaixuan"></text></view>
			
			<!-- 资源库选项 -->
			<view class='grace-filter-options' v-if="showingIndex == 1">
				<view :class="[index ==  dbIndex ? 'option current' : 'option']" v-for="(item, index) in facetDatabase" :key="index" @tap='changeDatabase' :data-itemid="index">
					{{item.name}}<text class="grace-iconfont icon-right" v-if="index ==  dbIndex"></text>
				</view>
			</view>
			<!-- 检索字段选项 -->
			<view class='grace-filter-options' v-if="showingIndex == 2">
				<view :class="[index ==  cateIndex ? 'option current' : 'option']" v-for="(item, index) in cateList" :key="index" @tap='changeCate' :data-itemid="index">
					{{item.name}}<text class="grace-iconfont icon-right" v-if="index ==  cateIndex"></text>
				</view>
			</view>
			<!-- 排序选项 -->
			<view class='grace-filter-options' v-if="showingIndex == 3">
				<view :class="[index ==  thIndex ? 'option current' : 'option']" v-for="(item, index) in thList" :key="index" @tap='changeTh' :data-itemid="index">
					{{item}}<text class="grace-iconfont icon-right" v-if="index ==  thIndex"></text>
				</view>
			</view>
			
			<!-- 分面导航筛选 start -->
			<view class='grace-filter-options' :style="{'width':'90%', 'height' : filterHeight, 'padding':'0'}" v-if="showingIndex == 99">
				<form @submit='formsubmit' @reset='formReset'>
					<scroll-view scroll-y="true" :style="{'height':filterHeight}">
						<view style="width:96%; padding:15upx 2%;">
							
							<view class="grace-h5 grace-blod">作者</view>
							<view style='padding:20upx 0;' class="grace-select-tips">
								<radio-group name="where1" @change="facetAuthorFunc">
									<label v-for="(item, index) in facetAuthor" :key="index" :class="[item.checked ? 'grace-checked' : '']">
										<radio :value="item.value" :checked="item.checked"></radio> {{item.name}}({{item.count}})
									</label>
								</radio-group>
							</view>
							
							<view class="grace-h5 grace-blod">作者单位</view>
							<view style='padding:20upx 0;' class="grace-select-tips">
								<radio-group name="where2" @change="facetAuthorUnitFunc">
									<label v-for="(item, index) in facetAuthorUnit" :key="index" :class="[item.checked ? 'grace-checked' : '']">
										<radio :value="item.value" :checked="item.checked"></radio> {{item.name}}({{item.count}})
									</label>
								</radio-group>
							</view>
							
							<view class="grace-h5 grace-blod">关键词</view>
							<view style='padding:20upx 0;' class="grace-select-tips">
								<radio-group name="where3" @change="facetKeywordsFunc">
									<label v-for="(item, index) in facetKeywords" :key="index" :class="[item.checked ? 'grace-checked' : '']">
										<radio :value="item.value" :checked="item.checked"></radio> {{item.name}}({{item.count}})
									</label>
								</radio-group>
							</view>
							
							<view class="grace-h5 grace-blod">年份</view>
							<view style='padding:20upx 0;' class="grace-select-tips">
								<radio-group name="where4" @change="facetYearFunc">
									<label v-for="(item, index) in facetYear" :key="index" :class="[item.checked ? 'grace-checked' : '']">
										<radio :value="item.value" :checked="item.checked"></radio> {{item.name}}({{item.count}})
									</label>
								</radio-group>
							</view>
							
							
							<!-- 占位视图组件 -->
							<view style="height:150upx;"></view>
						</view>
					</scroll-view>
					<!-- 按钮  -->
					<view class='grace-filter-buttons'>
						<view>
							重置
							<button form-type='reset'>重置</button>
						</view>
						<view>
							确定
							<button form-type='submit'>确定</button>
						</view>
					</view>
				</form>
			</view>
			<!-- 筛选 end -->
		</view>
		<!-- grace filter start -->
		
		<!-- 以下为演示内容 -->
		<view class="grace-padding" style="margin-top:80upx;">
			<view class="result-text">
				<view class="left">
					当前条件：{{searchText}} 
				</view>
				<view class="right">
					共 <text>{{dataCount}}</text> 条数据
				</view>
			</view>
			<view class="grace-news-list">
				
				<!-- <navigator>
					<view class="grace-news-list-items">
						<image src="../../../static/n2.jpg" class="grace-news-list-img grace-list-imgs-l" mode="widthFix"></image>
						<view class="grace-news-list-title">
							<view class="grace-news-list-title-main">[新闻资讯]一个项目经理不搞砸几个项目</view>
							<text class="grace-news-list-title-desc grace-text-overflow">百度新闻</text>
						</view>
					</view>
				</navigator> -->
				
				<block v-for="(item,index) in resultList" :key="index" >
					<view class="grace-news-list-items" @click="goDetail(index)">
						<view class="grace-news-list-title">
							<view class="grace-news-list-title-main">
								<rich-text :nodes="item.title"></rich-text>
							</view>
							<block v-if="item.author != ''">
								<view class="grace-news-list-title-desc grace-text-overflow">
									作者：<rich-text :nodes="item.author"></rich-text>
								</view>
							</block>
							
							<block v-if="item.keywords != ''">
								<view class="grace-news-list-title-desc grace-text-overflow">
									关键词：<rich-text :nodes="item.keywords"></rich-text>
								</view>
							</block>
							
							<block v-if="item.summary != ''">
								<view class="grace-news-list-title-desc grace-text-overflow">
									<rich-text :nodes="item.summary"></rich-text>
								</view>
							</block>
							
						</view>
					</view>
				</block>
				
				
			</view>
		</view>
		<view style="text-align:center;" v-show="dataShow">数据为空</view>		
	</view>
</template>
<script>
var _self;
import {
	mapState,
	mapMutations
} from 'vuex';
export default {
	computed: {
	    ...mapState(['databaseInfo','propertyInfo'])
	},
	data() {
		return {
			serverUrl : this.serverUrl,
			resultList: [],
			searchText: "",
			searchExpression: "",
			obj: {},
			dataCount: 0,
			//被展示的菜单
			showingIndex : 0,
			//资源库选项
			dbIndex : 0,
			//字段检索选项
			cateIndex: 0,
			cateList: [],
			//排序选项
			thIndex: 0,
			thList: ['相关度排序', '日期降序', '日期升序'],
			//是否第二次查询资源类型分面
			isFacetDatabase: 0,
			//筛选条件
			facetDatabase: [],
			facetAuthor:[],
			facetAuthorUnit: [],
			facetKeywords: [],
			facetYear: [],
			//二次筛选临时字段
			queryType: "",
			queryField: "",
			queryOrderby: "",
			queryOption: "",
			//筛选界面高度
			filterHeight : '300px',
			page: 1,
			dataShow: false
		}
	},
	//下拉刷新
	onPullDownRefresh: function() {
		// 重置分页及数据
		this.page = 1;
		this.resultList = [];
		this.getDataList();
	},
	// 加载更多
	onReachBottom: function() {
		this.getDataList();
	},	
	onLoad(e) {
		this.obj = JSON.parse(decodeURIComponent(e.obj));
		this.searchText = this.obj.searchText;
		this.searchExpression= this.obj.searchExpression;
		//console.log('searchExpression=' + this.searchExpression);
		
		this.getCommonProperty();
		
		//执行检索
		this.isFacetDatabase = 1;//执行资源库分面聚类
		this.getFacetList();
		this.resultList = [];
		this.page=1;
		this.getDataList();
	},
	onReady:function(){
		_self = this;
		uni.getSystemInfo({
			success: function (res) {
				var windowHeight = res.windowHeight;
				//获取头部标题高度
				uni.createSelectorQuery().select('#grace-filter-header').fields(
					{
						size: true,
					}, function (res) {
						if(!res){return ;}
						var sHeight = (windowHeight - res.height);
						_self.filterHeight = sHeight + 'px';
					}
				).exec();
			}
		});
		
	},
	methods : {
		// ...mapMutations(['setDatabaseInfo','setPropertyInfo']),
		changeDatabase:function(e){
			var tapIndex = e.target.dataset.itemid;
			this.dbIndex = tapIndex;
			this.showingIndex = 0;
			// console.log(this.facetDatabase[tapIndex].value);
			if(this.facetDatabase[tapIndex].value!="") {
				this.queryType = "$type:" + this.facetDatabase[tapIndex].value;
			}else {
				this.queryType = "";
			}
			//执行检索
			this.getFacetList();
			this.resultList = [];
			this.page=1;
			this.getDataList();
		},
		showOptions1:function(){if(this.showingIndex != 0){this.showingIndex = 0; return ;} this.showingIndex = 1;},
		showOptions2: function(){if(this.showingIndex != 0){this.showingIndex = 0; return ;} this.showingIndex = 2;},
		showOptions3: function(){if(this.showingIndex != 0){this.showingIndex = 0; return ;} this.showingIndex = 3;},
		showOptions99 : function(){if(this.showingIndex != 0){this.showingIndex = 0; return ;} this.showingIndex = 99;},
		changeCate: function (e) {
			var tapIndex = e.target.dataset.itemid;
			this.cateIndex = tapIndex;
			this.showingIndex = 0;
			// console.log(this.cateList[tapIndex].value);
			if(this.cateList[tapIndex].value!="") {
				this.queryField = "$" + this.cateList[tapIndex].value + ":";
			}else {
				this.queryField = "";
			}
			//执行检索
			// this.getFacetList();
			this.resultList = [];
			this.page=1;
			this.getDataList();
		},
		changeTh: function (e) {
			var tapIndex = e.target.dataset.itemid;
			this.thIndex = tapIndex;
			this.showingIndex = 0;
			// console.log(this.thList[tapIndex]);
			//执行检索
			// this.getFacetList();
			this.resultList = [];
			this.page=1;
			this.getDataList();
		},
		
		//提交条件
		formsubmit : function(e){
			// console.log(JSON.stringify(e.detail.value));
			let optionData = JSON.stringify(e.detail.value);
			
			let authorTmp = e.detail.value.where1;
			let authorUnitTmp = e.detail.value.where2;
			let keywordsTmp = e.detail.value.where3;
			let yearTmp = e.detail.value.where4;
			
			let queryTmp = "";
			
			if(authorTmp!=null && authorTmp!="") {
				queryTmp += " AND $author:" + authorTmp;
			}
			if(authorUnitTmp!=null && authorUnitTmp!="") {
				queryTmp += " AND $author_unit:" + authorUnitTmp;
			}
			if(keywordsTmp!=null && keywordsTmp!="") {
				queryTmp += " AND $keywords:" + keywordsTmp;
			}
			if(yearTmp!=null && yearTmp!="") {
				queryTmp += " AND $year:" + yearTmp;
			}
			
			this.queryOption = queryTmp;
			
			_self.showingIndex = 0;
			//执行检索
			// this.getFacetList();
			this.resultList = [];		
			this.page=1;
			this.getDataList();
		},
		//重置表单
		formReset : function(){
			//重置作者
			for (var i = 0; i < _self.facetAuthor.length; i++){
				_self.facetAuthor[i].checked= false;
			}
			_self.facetAuthor = _self.facetAuthor;
			//重置作者单位
			for (var i = 0; i < _self.facetAuthorUnit.length; i++) {
				_self.facetAuthorUnit[i].checked = false;
			}
			_self.facetAuthorUnit = _self.facetAuthorUnit;
			//重置关键词
			for (var i = 0; i < _self.facetKeywords.length; i++) {
				_self.facetKeywords[i].checked = false;
			}
			_self.facetKeywords = _self.facetKeywords;
			//重置年份
			for (var i = 0; i < _self.facetYear.length; i++) {
				_self.facetYear[i].checked = false;
			}
			_self.facetYear = _self.facetYear;
			
			_self.showingIndex = 0;
			
			//执行检索
			
			this.queryOption = "";
			
			this.getFacetList();
			this.resultList = [];
			this.page=1;
			this.getDataList();
		},
		
		//筛选-作者
		facetAuthorFunc: function (e) {
			var checkVal = e.detail.value;
			var currentVal = this.facetAuthor;
			for (var i = 0; i < currentVal.length; i++) {
				if (checkVal.indexOf(currentVal[i].value + '') != -1) {
					currentVal[i].checked = true;
				} else {
					currentVal[i].checked = false;
				}
			}
			this.facetAuthor = currentVal;
		},
		//筛选-作者单位
		facetAuthorUnitFunc: function (e) {
			var checkVal = e.detail.value;
			var currentVal = this.facetAuthorUnit;
			for (var i = 0; i < currentVal.length; i++) {
				if (checkVal.indexOf(currentVal[i].value + '') != -1) {
					currentVal[i].checked = true;
				} else {
					currentVal[i].checked = false;
				}
			}
			this.facetAuthorUnit = currentVal;
		},
		//筛选-关键词
		facetKeywordsFunc: function (e) {
			var checkVal = e.detail.value;
			var currentVal = this.facetKeywords;
			for (var i = 0; i < currentVal.length; i++) {
				if (checkVal.indexOf(currentVal[i].value + '') != -1) {
					currentVal[i].checked = true;
				} else {
					currentVal[i].checked = false;
				}
			}
			this.facetKeywords = currentVal;
		},
		//筛选-年份
		facetYearFunc: function (e) {
			var checkVal = e.detail.value;
			var currentVal = this.facetYear;
			for (var i = 0; i < currentVal.length; i++) {
				if (checkVal.indexOf(currentVal[i].value + '') != -1) {
					currentVal[i].checked = true;
				} else {
					currentVal[i].checked = false;
				}
			}
			this.facetYear = currentVal;
		},
		goDetail(index) {
			let obj = {
				id: this.resultList[index].id,
				type: this.resultList[index].type,
				title: this.resultList[index].title,
				author: this.resultList[index].author,
				create_time_str: this.resultList[index].create_time_str,
				cover: this.resultList[index].cover
			}
			if(this.resultList[index].type=='xwzx') {
				uni.navigateTo({
					url: "/pages/news/detail/detail?id=" + obj.id
				})
			}else if(this.resultList[index].type=='jsbk') {
				uni.navigateTo({
					url: "/pages/search/baike-detail/baike-detail?obj=" + encodeURIComponent(JSON.stringify(obj))
				})
			}else {
				uni.navigateTo({
					url: "/pages/search/detail/detail?obj=" + encodeURIComponent(JSON.stringify(obj))
				})
			}
			
		},
		getFacetList() {
			
			let queryTemp = "";
			
			this.facetAuthorUnit = [];
			this.facetAuthor = [];
			this.facetKeywords = [];
			this.facetYear = [];
			
			if(this.queryField.length>0) {
				queryTemp += this.queryField + this.searchText;
			}else {
				queryTemp += "("+ this.searchExpression + ")";
			}
			
			if(this.queryType.length>0) {
				queryTemp +=  " AND " + this.queryType;
			}
			
			if(this.queryOption.length>0) {
				queryTemp += this.queryOption;
			}
			
			//console.log("queryTemp=" + queryTemp);
			
			var data = {
				query: queryTemp,
				facetFields: "type;author;author_unit;keywords;year",
				limit: 5
			};
			uni.request({
				url: this.serverUrl + 'search-api/facet',
				header: {
					"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				data: data,
				method: "POST",
				success: (r) => {
					// console.log(r);
					if(r.data.code=='000000') {
						
						//类型 facetDatabase
						let typeTmp = r.data.data.type;
						if(this.isFacetDatabase==1) {
							this.facetDatabase.push({name:"全部资源",value:""});
							
							for(var key in typeTmp ){
								let databaseCn = '';
								for (var i = 0; i < this.databaseInfo.length; i++) {
									if(key==this.databaseInfo[i].key) {
										databaseCn = this.databaseInfo[i].value;
									}
								}
								this.facetDatabase.push({name:databaseCn,value:key});
							}
						}
						this.isFacetDatabase = 0; //重新赋值
						
						//作者
						let authorTmp = r.data.data.author;
						for(var key in authorTmp ){
// 							console.log(key);
// 							console.log(authorTmp[key]);
							this.facetAuthor.push({name:key,value:key,count:authorTmp[key],checked:false});
						}
						//作者单位
						let authorUnitTmp = r.data.data.author_unit;
						for(var key in authorUnitTmp ){
							this.facetAuthorUnit.push({name:key,value:key,count:authorUnitTmp[key],checked:false});
						}
						//关键词
						let keywordsTmp = r.data.data.keywords;
						for(var key in keywordsTmp ){
							this.facetKeywords.push({name:key,value:key,count:keywordsTmp[key],checked:false});
						}
						//年份
						let yearTmp = r.data.data.year;
						for(var key in yearTmp ){
							this.facetYear.push({name:key,value:key,count:yearTmp[key],checked:false});
						}
						
// 				　　　　　console.log(tmp);
// 						this.facetTypeData = r.data.data;
// 						for(var key in tmp ){
// 							console.log(key);
// 							console.log(tmp[key]);
// 						}
						
					}else {
						uni.showToast({
							title: r.data.message
						});
					}
				},
				fail: (data, code) => {
					console.log('fail' + JSON.stringify(data));
				}
			})
		},
		getDataList() {
			var hideload = 0;
			uni.showLoading();
			let queryTemp = "";
			
			if(this.queryField.length>0) {
				queryTemp += this.queryField + this.searchText;
			}else {
				queryTemp += "("+ this.searchExpression + ")";
			}
			
			if(this.queryType.length>0) {
				queryTemp +=  " AND " + this.queryType;
			}
			
			if(this.queryOption.length>0) {
				queryTemp += this.queryOption;
			}
			
			//console.log("queryTemp=" + queryTemp);
			var data = {
				query: queryTemp,
				showFields: "id;type;title;summary;author;keywords;database_cn;cover;create_time_str",
				highlightFields: "title;summary;keywords;author",
				pageNum: this.page,
				pageSize: 8
			};
			uni.request({
				url: this.serverUrl + 'search-api/search',
				header: {
				"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				data: data,
				method: "POST",
				success: (r) => {
					// console.log(r);
					if(r.data.code=='000000') {
						// this.resultList = r.data.data.data;
						this.dataCount = r.data.data.count;
						if (r.data.data.data.length < 1) {
							hideload = 1;
							uni.hideLoading();
							if (this.resultList.length < 1) {
								this.dataShow = true;
							}else{
								uni.showToast({
									title: "已经加载全部",
									icon: "none",
									duration: 1500
								});
							}
							return;
						}else{
							this.dataShow = false;
						}						
						var len = r.data.data.data.length;
						for (var i = 0; i < len; i++) {
							//资源类型
							let typeTmp = r.data.data.data[i].database_cn;
							//关键词
							let keywordsTmp = '';
							if(null!=r.data.data.data[i].keywords && r.data.data.data[i].keywords!='') {
								for (var m = 0; m < r.data.data.data[i].keywords.length; m++) {
									keywordsTmp += r.data.data.data[i].keywords[m] + " ";
								}
								keywordsTmp = keywordsTmp.substr(0,20);
							}
							
							//作者
							let authorTmp = '';
							if(null!=r.data.data.data[i].author && r.data.data.data[i].author!='') {
								for (var m = 0; m < r.data.data.data[i].author.length; m++) {
									authorTmp += r.data.data.data[i].author[m] + " ";
								}
								authorTmp = authorTmp.substr(0,20);
							}
							//摘要
							let summaryTmp = '';
							if(null!=r.data.data.data[i].summary && r.data.data.data[i].summary!='') {
								summaryTmp = r.data.data.data[i].summary[0];
								// summaryTmp = summaryTmp.substr(0,90);
							}
							
							//封面
							let coverTmp = '';
							if(null!=r.data.data.data[i].cover && r.data.data.data[i].cover!='') {
								coverTmp = r.data.data.data[i].cover[0]
							}
							
							var tmpObj = {
								id: r.data.data.data[i].id[0],
								type: r.data.data.data[i].type[0],
								title: ((this.page-1)*8+(i+1)) + ". ["+ typeTmp +"] " + r.data.data.data[i].title[0], 
								create_time_str: r.data.data.data[i].create_time_str[0], 
								cover: coverTmp, 
								typeTmp: typeTmp,
								author: authorTmp,
								keywords: keywordsTmp,
								summary: summaryTmp
							};
							this.resultList = this.resultList.concat(tmpObj);
						}
						this.page++;
					}else {
						uni.showToast({
							title: r.data.message
						});
					}
				},
				fail: (data, code) => {
					console.log('fail' + JSON.stringify(data));
				},
				complete: r => {
					if (hideload == 0) {
						uni.hideLoading();
					}
					uni.stopPullDownRefresh();
				}
			})
		},
		// 查询公共字段
		getCommonProperty() {
			
			this.cateList = [];
			this.cateList.push({name:"全部字段",value:""});
			
			var data = {
				generalSearchField: "1",
				pageNumber: 1,
				pageSize: 5
			}; 
			uni.request({
				url: this.serverUrl + 'search-api/getCommonProperty',
				header: {
					"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				data: data,
				method: "POST",
				success: (r) => {
					// console.log(r);
					if(r.data.code=='000000') {
						// this.cateList = r.data.data;
						
						var len = r.data.data.length;
						for (var i = 0; i < len; i++) {
							var tmpObj = {
								name: r.data.data[i].nameCn,
								value: r.data.data[i].nameEn
							};
							this.cateList.push(tmpObj);
						}
						
					}else {
						uni.showToast({
							title: r.data.message
						});
					}
				},
				fail: (data, code) => {
					console.log('fail' + JSON.stringify(data));
				}
			})
		}
		//
		
	}
}
</script>
<style>
	.grace-news-list-title {
		margin: 8upx 0;
	}
	.grace-news-list-title-main {
		font-size: 30upx;
	}
	rich-text{
		display:inline-block;
	}
	.result-text {
		margin-top: 20upx;
		display:flex;
		flex-direction:row !important;
	}
	.result-text .left {
		width: 49%;
		display:flex;
		justify-content: flex-start;
	}
	.result-text .right {
		width: 49%;
		display:flex;
		justify-content: flex-end;
	}
	.result-text text {
		color: #FF0000;
		/* margin: 5upx 0; */
		font-weight: bold;
	}
	.grace-news-list {
		margin-top: 0upx;
	}
	.grace-news-list-title-desc {
		margin-top: 6upx;
		max-height: 40upx;
	}
	.grace-news-list-items {
		margin-bottom: 5upx;
	}
	
	.grace-filter-buttons view:last-child {
		background-color: #417dc9;
	}
	
</style>